'''
Evaluation Tasks

The feedback task performs selection and reproduction.
'''
import random
from dexen.libs import ranking
from dexen import BaseSlaveTask
from dexen.libs.ranking import ParetoRanking
import settings

#Function to create new individuals
def create_children(ranked):
    parents = [x.ind for x in ranked[:len(ranked)/2]]
    assert len(parents) % 2 == 0
    random.shuffle(parents)
    children = []
    for i in range(0, len(parents), 2):
        child1, child2 = parents[i].reproduce(parents[i+1])
        children.append(child1)
        children.append(child2)
    return children

#Function to create new individuals
def kill_individuals(ranked):
    deceased = [x.ind for x in ranked[len(ranked)/2:]]
    for ind in deceased:
        ind.kill()

#Slave task for feedback
class FeedbackTask(BaseSlaveTask):
    def __init__(self):
        pass
    def __execute__(self, master_state, inds):
        #rank individuals
        p_ranking = ParetoRanking(inds)
        p_ranking.register_score("score_area", settings.EVAL_AREA_TYPE)
        p_ranking.register_score("score_vol", settings.EVAL_VOL_TYPE)
        ranked = p_ranking.rank() # returns list of RankResult sorted by rank
        #create children using high rank individuals
        children = create_children(ranked)
        #kill the low rank individuals
        kill_individuals(ranked)
        #return all the inds (inds + children)
        return inds + children
        

    